package com.eninus.notification.ios;
import java.nio.ByteBuffer;

import org.apache.commons.codec.binary.Base64;


public class IOSNotificationPacket {
	ByteBuffer bbuffer;
	byte command;
	int identifier=-1;
	int expiry=-1;
	short tokenLength;
	String deviceToken;
	short payloadLength;
	String payload;
	
	long millisecondsSince1970;
	public IOSNotificationPacket() throws Exception {
		bbuffer=ByteBuffer.allocateDirect(303);
	}
	public boolean pack()throws Exception{
		bbuffer.clear();
		if(identifier<0||expiry<0){
			command=0;
			bbuffer.put(command);
		}else{
			command=1;
			bbuffer.put(command);
			bbuffer.putInt(identifier);
			bbuffer.putInt(expiry);
		}
		
		byte[] rawToken=Base64.decodeBase64(deviceToken);
		tokenLength=(short)rawToken.length;
		bbuffer.putShort(tokenLength);
		bbuffer.put(rawToken);
		byte[] payLoadBytes=payload.getBytes("UTF8");
		payloadLength=(short)payLoadBytes.length;
		bbuffer.putShort(payloadLength);
		if(payloadLength>256){
			return false;
		}
		bbuffer.put(payLoadBytes);
		
		return true;
	}
}
